package com.mazaiting.web.holder;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * Spring 上下文处理对象
 *
 * @author mazaiting
 * @create_time 2022/4/6 12:22
 */
@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    /**
     * 全局应用上下文
     */
    private static ApplicationContext applicationContext;

    /**
     * 从变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     * @param name 名称
     * @param <T> 泛型
     * @return bean
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     * @param clazz 字节码
     * @param <T> 泛型
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @param name 名字
     * @param clazz 字节码
     * @param <T> 泛型
     * @return bean
     */
    public static <T> T getBean(String name, Class<T> clazz){
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        getApplicationContext().publishEvent(event);
    }

    @Override
    public void destroy() {
        applicationContext = null;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        Assert.notNull(applicationContext, "applicationContext 为 null, 请先注入");
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
